package com.swxy.club.exceptions;



import com.swxy.club.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.net.ConnectException;
import java.util.Objects;


/**
 * @author 易
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e){
        log.error("异常信息{}",e.getMessage());
        return Result.error(500,"系统发生了一个问题，请稍后重试");
    }

    @ExceptionHandler(value = PermissionDeniedException.class)
    @ResponseBody
    public Result notFoundExceptionHandler(PermissionDeniedException e){
        log.error("异常信息{}",e.getMessage());
        return Result.error(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(value = UserNotFoundException.class)
    @ResponseBody
    public Result badRequestExceptionHandler(UserNotFoundException e){
        log.error("异常信息{}",e.getMessage());
        return Result.error(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(value = ValidationException.class)
    @ResponseBody
    public Result validationExceptionHandler(ValidationException e){
        log.error("异常信息{}",e.getMessage());
        return Result.error(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(value = UnauthorizedException.class)
    @ResponseBody
    public Result unauthorizedExceptionHandler(UnauthorizedException e){
        log.error("异常信息{}",e.getMessage());
        return Result.error(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseBody
    public Result illegalArgumentExceptionExceptionHandler(IllegalArgumentException e){
        log.error("异常信息{}",e.getMessage());
        return Result.error(405,e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        log.error("异常信息{}",e.getMessage());
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return Result.error(406,message);
    }

    @ExceptionHandler(value = CheckinCodeException.class)
    @ResponseBody
    public Result checkinCodeExceptionHandler(CheckinCodeException e){
        log.error("异常信息{}",e.getMessage());
        String message = Objects.requireNonNull(e.getMessage());
        return Result.error(406,message);
    }



}
